package com.share.hope.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.hope.entity.ProductsInfo;
import com.share.hope.entity.UserInfo;
import com.share.hope.entity.page.Condition;
import com.share.hope.entity.page.PageQueryVo;
import com.share.hope.entity.result.PageR;
import com.share.hope.entity.result.R;
import com.share.hope.mapper.ProductsMapper;
import com.share.hope.service.ProductsService;
import com.share.hope.service.UserInfoService;
import com.share.hope.vo.ProductsPageQueryVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class ProductsServiceImpl extends BaseServiceImpl<ProductsMapper, ProductsInfo> implements ProductsService {

   private final UserInfoService userInfoService;

    @Override
    public R<String> createProduct(ProductsInfo productsInfo) {
        if (this.save(productsInfo)) {
            return R.ok("添加成功");
        }
        return R.error("添加失敗");
    }

    @Override
    public R<String> updateProduct(ProductsInfo productsInfo) {
        if (this.updateById(productsInfo)) {
            return R.ok("修改成功");
        }
        return R.error("修改失敗");
    }

    @Override
    public R<String> deleteProduct(Long productId) {
        if (this.removeById(productId)) {
            return R.ok("刪除成功");
        }
        return R.error("刪除失敗");
    }

    @Override
    public R<PageR<ProductsInfo>> pageProduct(PageQueryVo<ProductsPageQueryVo> queryVo) {
        ProductsPageQueryVo query = queryVo.getQuery();
        LambdaQueryWrapper<ProductsInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(query.getName()), ProductsInfo::getName, query.getName());
        wrapper.eq(StringUtils.hasText(query.getId()), ProductsInfo::getId, query.getId());
        return R.success(new PageR<>(this.page(Condition.getPage(queryVo.getPage()), wrapper)));

    }


    @Override
    public R<String> exchangeCollect(Long userId, Long productId) {
        UserInfo userInfo = userInfoService.getById(userId);
        ProductsInfo productsInfo = this.getById(productId);

        Double price = productsInfo.getPrice();
        String name = productsInfo.getName();
        userInfo.setLoveCoin(userInfo.getLoveCoin() - price);
        if (userInfoService.updateById(userInfo)) {
            return R.ok("兑换成功, 兑换了" + name + ", 消耗了" + price + "爱心币.");
        }
        return R.error("兑换失败");
    }
}
